import random

from django.shortcuts import render
from rest_framework.response import Response
from rest_framework.views import APIView
from sympy import Q

from user.models import UserModel
from user.ser import UserSer

import re

from utils.MyJWT import myjwt
from utils.MyRedis import myredis

import re

from utils.MyRedis import MyRedis
from utils.Sendcode import SendCode


# Create your views here.
class LoginView(APIView):

    def post(self,request):
        # jwt工具包实例化

        # 账号
        account = request.data.get('account')
        # 密码
        password = request.data.get('password')
        user = UserModel.objects.filter(Q(phone=account)&Q(password=password)).first()
        ser = UserSer(user)
        if user:
            Response({"msg":"登录成功","token":myjwt.getToken(ser.data["id"],ser.data["name"]),"userid":ser.data["id"]})
        else:
            return Response({"msg":"登录失败"})
class CaptchaAPIView(APIView):
    def get(self,request):
        # 手机号
        phone = request.query_params.get('phone')
        # re正则校验
        data = re.match(r'^1[3-9]\d{9}$',phone)
        if data:
            # 手机验证码实例化
            sendcode = SendCode()
            # Redis实例化
            myredis = MyRedis()
            # 随机生成验证码
            code = random.randint(1,9999)
            # 使用redis实例化中的方法将phone手机号作为键名code随机生成的验证码作为值设置有效时长60秒
            myredis.setex(phone,code,60)
            # 得到结果看是否已经发送过去验证码
            type = sendcode.send_message(phone,code)
            if type:
                return Response({"code":"200","captcha":code})
            else:
                return Response({"code":"400","msg":"验证码发送失败"})
        else:
            return Response({"code":"404","msg":"手机号格式不正确"})


# 验证码登录
class CaptLogin(APIView):
    def post(self, request):
        phone = request.data.get('phone')
        captcha = request.data.get('captcha')
        # 正则验证
        res = re.match(r'^1[3-9]\d{9}$', phone)
        if res:
        # 假设验证码在Redis中的键是 phone:captcha，值是验证码的哈希值
            sss = myredis.getstr(phone)
            if sss == captcha:
                user = UserModel.objects.filter(phone=phone).first()
                ser = UserSer(user)
                return Response({"msg": "登录成功", "userid": ser.data["id"], "token": myjwt.getToken(user.id, phone)})
            else:
                return Response({"msg": "登录失败"})
        else:
            return Response({"msg":"手机号格式错误"})










